'use strict';

const express = require('express');
const dbutility = require('../../common/dbutility');
const gputility = require('../../common/gputility');
const cabutility = require('../../common/cabutility');
const logger = require('../../common/logutility').logger('dlvExpCho');
let router = express.Router();

router.get('/', function(req, res) {
    gputility.excuteGP(getGP(req, res));
});

router.post('/', function(req, res) {
    gputility.excuteGP(postGP(req, res));
});

function* getGP(req, res) {
    try {
        req.session.expDlv.expCabinetNo = null;
        res.render('./cou/dlvExpCho');
    } catch (e) {
        logger.error(e);
        res.redirect('/error');
    }
}

function* postGP(req, res) {
    try {
        let cabType = req.body.cabType;
        let cab = yield dbutility.cabModel.getCabByCabTypeNotInUse(cabType);
        if (cab) {
            //开启快递柜
            let cabPortName = cab.cabPortName;
            let cabCheckCmd = cab.cabCheckCmd;
            let cabOpenCmd = cab.cabOpenCmd;
            let cabOpenStatus = cab.cabOpenStatus;

            //执行快递柜开柜命令
            let cmdOpenRepeat = 0;
            let cmdExcuteSucceed;;
            while ((!cmdExcuteSucceed) && cmdOpenRepeat < 3) {
                cmdExcuteSucceed = yield cabutility.openCab(cabPortName, cabOpenCmd);
                cmdOpenRepeat += 1;
            }

            //取得快递柜开闭状态
            let cmdCheckRepeat = 0;
            let cabLockStatus;
            while (cmdCheckRepeat < 3 && cabLockStatus !== cabOpenStatus) {
                cabLockStatus = yield cabutility.checkCab(cabPortName, cabCheckCmd)
                cmdCheckRepeat += 1;
            }

            if (cabLockStatus !== cabOpenStatus) {
                res.render('./cou/dlvExpCho', { errorInfo: '所选类型的快递柜开启失败，请联系系统管理员！' });
            } else {
                req.session.expDlv.expCabinetNo = cab.cabNo;
                res.redirect('/dlvExpTest');
            }
        } else {
            res.render('./cou/dlvExpCho', { errorInfo: '该型号快递柜已满,请选择其他型号！' });
        }
    } catch (e) {
        logger.error(e);
        res.redirect('/error');
    }
}

module.exports = router;